package com.wisely.xxboot.batch;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.batch.item.validator.Validator;
import org.springframework.batch.item.validator.ValidationException;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 *
 * @author shengping
 * @version 1.0
 * @date 2017/7/3
 */
public class CsvBeanValidator<T> implements Validator<T>,InitializingBean {

    private javax.validation.Validator validator;

    @Override
    public void afterPropertiesSet() throws Exception{
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.usingContext().getValidator();
    }

    @Override
    public void validate(T value) throws ValidationException{
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(value);//2
        if(constraintViolations.size()>0){
            StringBuilder message = new StringBuilder();
            for(ConstraintViolation<T> constraintViolation : constraintViolations){
                message.append(constraintViolation.getMessage()+"\n");
            }
            throw new ValidationException(message.toString());
        }

    }
}
